﻿using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    abstract class Watermarker : SinglePdfManipulator
    {
        protected const int MemoryStreamCapacity = 10 * 1024; //10KB

        protected WatermarkOption WatermarkOption
        {
            get
            {
                return (WatermarkOption)option;
            }
        }

        protected abstract PdfSharp.Drawing.XSize ElementSize
        {
            get;
        }

        protected TataLayout Layout
        {
            get
            {
                return WatermarkOption.Layout;
            }
        }

        protected abstract void AddWatermark(PdfSharp.Drawing.XGraphics gfx);

        protected override void Manipulate()
        {
            WatermarkItem watermarkItem = workItem as WatermarkItem;
            int numOfPages = stamper.Reader.NumberOfPages;
            PdfContentByte underContent;

            PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();
            PdfSharp.Pdf.PdfPage page = document.AddPage();
            page.Width = ElementSize.Width;
            page.Height = ElementSize.Height;
            PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page,
                PdfSharp.Drawing.XGraphicsPdfPageOptions.Prepend);

            AddWatermark(gfx);

            MemoryStream ms = new MemoryStream(MemoryStreamCapacity);
            document.Save(ms);
            PdfReader rder = new PdfReader(ms.ToArray());
            PdfImportedPage importedPage = stamper.GetImportedPage(rder, 1);

            int from = watermarkItem.From;
            int to = watermarkItem.To;
            int offset = from <= to ? 1 : -1;
            try
            {
                for (int i = from - offset; i != to; i += offset)
                {
                    underContent = stamper.GetUnderContent(i + offset);

                    iTextSharp.text.Rectangle pageRect = stamper.Reader.GetPageSizeWithRotation(i + offset);
                    SizeF pageSize = new SizeF(pageRect.Width, pageRect.Height);

                    Matrix transformationMatrix = this.Layout.PerformLayoutOnPdfPage(
                        pageSize, ElementSize.ToSizeF());
                    underContent.Transform(transformationMatrix);
                    underContent.AddTemplate(importedPage, 0, 0);
                }
            }
            finally
            {
                SharpHelper.ClosePdf(rder, ms);
            }
        }

    }
}
